<template>
  <MainContainer class="p-5">
    <div class="details">
      <div>
        <div>
          <img class="w-[3vw] select-none" :src="robot" />
          <span>{{ buildingName }}</span>
        </div>
      </div>
      <div>
        <div class="font info">电梯信息</div>
        <div class="font">设备名称：{{ buildingDetail.deviceName }}</div>
        <div class="font">设备编码：{{ buildingDetail.deviceUnique }}</div>
        <div class="font">
          设备状态：{{ buildingDetail.controllerDeviceUnique }}
        </div>
      </div>
      <div>
        <el-button type="primary" @click="openBindingDialog()"
          >绑定电梯</el-button
        >
      </div>
    </div>
    <div class="flex">
      <el-button type="primary" @click="openDialog()">+添加地图</el-button>
    </div>
    <MyTable
      v-loading="loading"
      class="my-2"
      :data="mapDetail"
      :columns="columns"
      :is-show-selection="false"
    ></MyTable>
    <el-pagination
      v-model:currentPage="params.page"
      v-model:page-size="params.limit"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      class="justify-end"
      @size-change="handleQuery"
      @current-change="handleQuery"
    />
    <MyFormDialog
      v-model:visible="dialogVisible"
      v-model:formData="formData"
      :title="dialogTitle"
      :options="createFormOptions"
      :loading="loading"
      @confirm="handleConfirm"
    ></MyFormDialog>
    <ElevatorBinding
      v-model:visible="bindingDialogVisible"
      title="绑定电梯"
      :loading="loading"
      :list="elevatorList"
      @confirm="handleBindingConfirm"
    ></ElevatorBinding>
  </MainContainer>
</template>
<script setup lang="jsx">
import robot from "@/assets/images/disinfect/building.png";
import MainContainer from "@/components/MainContainer.vue";
import MyFormDialog from "@/components/MyFormDialog.vue";
import MyTable from "@/components/MyTable.vue";
import ElevatorBinding from "@/views/disinfect/MapManage/components/ElevatorBinding.vue";
import { getToken } from "@/utils/auth.js";
import { getBuildingDetail } from "@/api/building";
import { getElevator } from "@/api/elevator";
import { useRoute } from "vue-router";
import {
  getDisinfectMapById,
  getDisinfectMap,
  deleteDisinfectMap,
  updateDisinfectMap,
  createDisinfectMap,
} from "@/api/robot-disinfect-map";
import { onMounted, ref, onUnmounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

const createFormOptions = [
  {
    label: "地图名称",
    prop: "name",
    rules: {
      required: true,
      message: "必填",
    },
  },
  {
    label: "所在楼层",
    prop: "storey",
    rules: {
      required: true,
      message: "必填",
    },
  },
  {
    label: "上传地图",
    prop: "url",
    rules: {
      required: true,
      message: "必填",
    },
    customRender() {
      return (
        <el-form-item class="w-full">
          <el-input v-model={formData.value.url} disabled />
          <el-upload
            class="my-4"
            headers={{ Authorization: getToken() }}
            show-file-list={false}
            on-success={onSuccess}
            before-upload={beforeUpload}
            limit={1}
            action="http://119.91.145.64:8081/api/file/upload"
            accept="image/*"
          >
            <el-button type="primary" data-test="choose-btn" plain>
              选择文件
            </el-button>
          </el-upload>
        </el-form-item>
      );
    },
  },
];

function onSuccess(response) {
  formData.value.url = response.message;
  loading.value = false;
}

function beforeUpload() {
  loading.value = true;
}
const columns = [
  {
    prop: "id",
    label: "编号",
  },
  {
    label: "名称",
    prop: "name",
  },
  {
    label: "所在楼层",
    prop: "storey",
  },
  {
    label: "地图预览",
    prop: "url",
    customRender(row) {
      return (
        <el-image
          style="width: 100px; height: 64px"
          src={row.url}
          fit="cover"
        />
      );
    },
  },
  {
    label: "操作",
    prop: "action",
    minWidth: 100,
    customRender(row) {
      return (
        <div>
          <el-button link onClick={() => handleDelete(row.id)}>
            删除
          </el-button>
          <el-button
            class="!text-[#707bdf]"
            link
            onClick={() => openDialog(row.id)}
          >
            编辑
          </el-button>
        </div>
      );
    },
  },
];

onMounted(() => {
  getDetail();
  getMapList();
});

let route = useRoute();

const loading = ref(false);

const buildingDetail = ref({
  deviceName: "",
  deviceUnique: "",
  controllerDeviceUnique: "",
});
const buildingName = ref("");
const buildingEid = ref(0);
//获取楼栋详情
async function getDetail() {
  const { data } = await getBuildingDetail(route.query.id);
  // 获取电梯信息
  if (data.elevator) {
    buildingDetail.value = data.elevator;
  }
  buildingEid.value = data.eid;
  buildingName.value = data.name;
}

//获取地图列表
const mapDetail = ref([]);
const total = ref(0);
const params = ref({
  page: 1,
  limit: 10,
});
async function getMapList() {
  loading.value = true;
  try {
    const res = await getDisinfectMapById(route.query.id);
    loading.value = false;
    mapDetail.value = res.data.list || res.data;
    total.value = res.data.total;
  } catch {
    loading.value = false;
  }
}

//获取单条地图数据
const formData = ref({});
const dialogTitle = ref("");

function openDialog(id) {
  dialogTitle.value = id ? "编辑" : "新增";
  if (id) {
    getOne(id);
  }
  dialogVisible.value = true;
}

async function getOne(id) {
  const res = await getDisinfectMap(id);
  res.data.list.map((item) => {
    if (item.id === id) {
      formData.value = item;
      return;
    }
  });
}

//提交表单
function handleConfirm(data) {
  data.bid = parseInt(route.query.id);
  data.eid = buildingEid.value;
  if (data.id) {
    handleUpdate(data.id, data);
  } else {
    handleCreate(data);
  }
}

const dialogVisible = ref(false);

// 新增/编辑
async function handleCreate(data) {
  loading.value = true;
  try {
    await createDisinfectMap(data);
    dialogVisible.value = false;
    loading.value = false;
    handleQuery();
  } catch {
    loading.value = false;
  }
}

async function handleUpdate(id, data) {
  loading.value = true;
  try {
    await updateDisinfectMap(id, data);
    dialogVisible.value = false;
    loading.value = false;
    handleQuery();
  } catch {
    loading.value = false;
  }
}

const bindingDialogVisible = ref(false);

const elevatorList = ref([]);

async function openBindingDialog() {
  bindingDialogVisible.value = true;
  const res = await getElevator();
  elevatorList.value = res.data.list;
}

function handleBindingConfirm(v) {
  buildingDetail.value.controllerDeviceUnique = v.controllerDeviceUnique;
  buildingDetail.value.deviceName = v.deviceName;
  buildingDetail.value.deviceUnique = v.deviceUnique;
}

// 删除
const timer = ref();
async function handleDelete(id) {
  loading.value = true;
  try {
    await ElMessageBox.confirm("是否删除该地图信息?", "Warning", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        deleteDisinfectMap(id);
        timer.value = setTimeout(() => {
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          getMapList();
        }, 100);
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "已取消",
        });
      });
    loading.value = false;
  } catch {
    loading.value = false;
  }
}

onUnmounted(() => {
  clearTimeout(timer.value);
  timer.value = "";
});
function handleQuery() {
  getDetail();
  getMapList();
}
</script>
<style lang="scss" scoped>
.details {
  width: 100%;
  height: 137px;
  background: #f1f3fa;
  border: 1px solid #dddddd;
  border-radius: 10px;
  margin: 16px 0;
  padding: 16px;
  display: flex;
  justify-content: space-around;
  align-items: center;

  div:nth-child(1) {
    display: flex;
    align-items: center;

    .svg-icon {
      font-size: 42px;
    }

    span {
      font-size: 18px;
      font-weight: 200;
      color: #000000;
    }
  }

  .font {
    font-size: 16px;
    font-weight: 200;
    color: #949494;
  }

  .info {
    line-height: 40px;
    font-weight: 400;
    color: #202020;
  }

  .online {
    display: inline-block;
    width: 7px;
    height: 7px;
    background: #ff9940;
    border-radius: 50%;
    margin-bottom: 2px;
  }
}
</style>
